using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using static SmartSite.Common.CheckingNullArgument;

namespace SmartSite.Frame
{
    public class StringField : Field<string>, IValueField<string>
    {
        static Encoding DefaultEncoding = Encoding.ASCII;

        public StringField(List<byte> buffer, BitUnit index, BitUnit count)
        : base(buffer, index, count) { }

        public StringField(IBytesBuffer buffer, BitUnit index, BitUnit count)
        : base(buffer, index, count) { }

        public StringField(IField field, BitUnit count)
        : base(field, count) { }

        public override string Value
        {
            get
            {
                return TrimZero
                (
                    DefaultEncoding.GetString(Buffer.ToArray(), Index.CeilToByteUnit(), Count.FloorToByteUnit())
                );
            }

            set
            {
                CheckingNull(value, nameof(value));
                if (DefaultEncoding.GetByteCount(value) > Count.FloorToByteUnit())
                    throw new ArgumentOutOfRangeException(nameof(value));

                byte[] buffer = new byte[Count.FloorToByteUnit()];
                DefaultEncoding.GetBytes(value, 0, value.Length, buffer, 0);
                BitsVariable bits = new BitsVariable(buffer.ToList(), 0, Count);
                bits.CopyTo(BitsVariable);
            }
        }

        string TrimZero(string str)
        {
            int eof = str.IndexOf('\0');
            return eof == -1 ? str : str.Substring(0, eof);
        }

    }
}